<template>
  <div class="chat-header">
    <div class="header-content">
      <div class="left-content">
        <a-space align="center">
          <a-badge :count="count">
            <a-avatar v-if="GroupStore.avatarMaxUrl">
              <img alt="avatar" :src="GroupStore.avatarMaxUrl" />
            </a-avatar>
            <a-avatar v-else>
              <icon-user-group />
            </a-avatar>
          </a-badge>          
        </a-space>
      </div>
      <a-button type="primary" size="small" @click="handleGroupFriendTask">创建任务</a-button>
    </div>
  </div>
  <a-table
    :data="friendlist"
    :columns="columns"
    :loading="loading"
  >
  </a-table>
  
</template>

<script lang="ts" setup>
  import { ref, defineProps, watch } from 'vue';
  import { useGroupStore } from '@/store';
  import { Message } from '@arco-design/web-vue';
  import type { TableColumnData } from '@arco-design/web-vue';
  import { getMemberList } from '@/api/task';

  const emit = defineEmits(['handleGroupFriendTask']);
  const props = defineProps<{
    selectedWxid: string;
    selectedAvatar: string;
  }>();
  const GroupStore = useGroupStore();
  // 分页相关
  const loading = ref(false);
  const columns: TableColumnData[] = [
    {
      title: '成员',
      dataIndex: 'wxid',
      width: 200,
    }
  ];
  // 组件状态
  const friendlist = ref<any[]>([]);
  const count = ref(0);

  // 获取消息列表
  const getfriendlist = async () => {
    loading.value = true;
    try {
      const res: any = await getMemberList({
        selectedWxid: props.selectedWxid,
        groupwxid: GroupStore.groupwxid,
      });
      if (res.code === 20000) {
        friendlist.value = res.data || [];
        count.value = res.count;
        loading.value = false;
      } else {
        Message.error(res.msg || '获取消息失败');
      }
    } catch (error) {
      Message.error('获取消息失败');
    }
  };

  const handleGroupFriendTask = async () => {
    // 调用父组件
    emit('handleGroupFriendTask', {
        selectedWxid: props.selectedWxid,
        groupwxid: GroupStore.groupwxid,
        friendlist: friendlist.value,
        content: `我是群聊“${GroupStore.groupnick}”的好友`
    })
  }

  // 监听群变化
  watch(
    () => GroupStore.groupwxid,
    (newWxid) => {
      if (newWxid) {
        friendlist.value = [];
        getfriendlist(); 
      }
    },
    { immediate: true }
  );
</script>

<style scoped>
  .chat-header {
    display: flex;
    padding: 10px;
    width: 100%;
    border: 1px solid var(--color-border);
  }

  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
  }

  .left-content {
    display: flex;
    align-items: center;
  }

  .right-content {
    display: flex;
    align-items: center;
  }

  .friend-name {
    margin-left: 8px;
    font-weight: 500;
  }
</style>
